package com.april.product.exception;

import com.april.common.enums.AppHttpCodeEnum;
import com.april.common.utils.Result;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @Package : com.april.product.exception
 * @Author : xz
 * @Date : 2024-04-20 0:44
 * @Desc :
 */
@RestControllerAdvice
public class AprilMallProductException {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();

        ex.getBindingResult().getFieldErrors().forEach(fieldError -> {
            errors.put(fieldError.getField(), fieldError.getDefaultMessage());
        });

        // 可以添加额外的逻辑，比如记录日志等

        return Result.error(AppHttpCodeEnum.DATA_EXCEPTION.getCode(), AppHttpCodeEnum.DATA_EXCEPTION.getMsg())
                .put("data", errors);
    }

    @ExceptionHandler(value = Throwable.class)
    public Result handleException(Throwable throwable) {
        return Result.error();
    }
}
